package com.ruoyi.purchase.helper;

import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.purchase.domain.ChangeRecord;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CompareObjectField {

    public static List<ChangeRecord> compareObjects(Object obj1, Object obj2){
        // 检查两个对象是否为null或不是同一个类的实例
        if (obj1 == null || obj2 == null || !obj1.getClass().equals(obj2.getClass())) {
            throw new IllegalArgumentException("Objects must not be null and must be of the same class");
        }

        Class<?> clazz = obj1.getClass();
        Field[] fields = clazz.getDeclaredFields();
        List<ChangeRecord> differences = new ArrayList<>();

        for (Field field : fields) {
            try {
                field.setAccessible(true); // 使私有字段可访问

                Object value1 = field.get(obj1);
                Object value2 = field.get(obj2);

                // 比较字段值，如果不同则记录下来
                if (!Objects.equals(value1, value2)) {
                    String detailInformation = " " + value1 + " 修改为 " + value2 + " ";
                    differences.add(new ChangeRecord(field.getName(),detailInformation));
                }
            } catch (IllegalAccessException e) {
                // 处理非法访问异常
                throw new GlobalException(e.getMessage());
            } catch (IllegalArgumentException e) {
                // 处理非法参数异常
                throw new GlobalException(e.getMessage());
            } catch (SecurityException e) {
                // 处理安全异常
                throw new GlobalException(e.getMessage());
            } catch (Exception e) {
                // 捕获所有其他类型的异常
                throw new GlobalException(e.getMessage());
            } finally {
                // 确保字段访问权限被重置（可选，取决于安全性需求）
                field.setAccessible(false);
            }
        }
        return differences;
    }
}
